#!/usr/bin/python
# -*- coding:utf-8 -*-
# @FileName : Test2.py
# Author    : myh


import numpy as np
import torch
from matplotlib_inline import backend_inline
from torch.distributions import multinomial
import matplotlib.pyplot as plt
from d2l import torch as d2l


import os


def use_svg_display():  #@save
    """使用svg格式在Jupyter中显示绘图"""
    backend_inline.set_matplotlib_formats('svg')

def set_figsize(figsize=(3.5, 2.5)):  #@save
    """设置matplotlib的图表大小"""
    use_svg_display()
    d2l.plt.rcParams['figure.figsize'] = figsize

#@save
def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend):
    """设置matplotlib的轴"""
    axes.set_xlabel(xlabel)
    axes.set_ylabel(ylabel)
    axes.set_xscale(xscale)
    axes.set_yscale(yscale)
    axes.set_xlim(xlim)
    axes.set_ylim(ylim)
    if legend:
        axes.legend(legend)
    axes.grid()

#@save
def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,
         ylim=None, xscale='linear', yscale='linear',
         fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None):
    """绘制数据点"""
    if legend is None:
        legend = []

    set_figsize(figsize)
    axes = axes if axes else d2l.plt.gca()

    # 如果X有一个轴，输出True
    def has_one_axis(X):
        return (hasattr(X, "ndim") and X.ndim == 1 or isinstance(X, list)
                and not hasattr(X[0], "__len__"))

    if has_one_axis(X):
        X = [X]
    if Y is None:
        X, Y = [[]] * len(X), X
    elif has_one_axis(Y):
        Y = [Y]
    if len(X) != len(Y):
        X = X * len(Y)
    axes.cla()
    for x, y, fmt in zip(X, Y, fmts):
        if len(x):
            axes.plot(x, y, fmt)
        else:
            axes.plot(y, fmt)
    set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend)

def f(x):
    return 3 * x ** 2 - 4 * x



x = np.arange(0, 3, 0.1)
plot(x, [f(x), 2 * x - 3], 'x', 'f(x)', legend=['f(x)', 'Tangent line (x=1)'])
d2l.plt.show()

# os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
#
# fair_probs = torch.ones([6]) / 6
# num_1 =multinomial.Multinomial(1, fair_probs).sample()
# print('1',num_1)
#
# # 将结果存储为32位浮点数以进行除法
# counts = multinomial.Multinomial(1000, fair_probs).sample()
#  # 相对频率作为估计值
# print('2',counts / 1000 )
#
# # 做50次实验，每次样本个数增加100次
# counts = multinomial.Multinomial(100, fair_probs).sample((50,))
# # print("counts=",counts)
# cum_counts = counts.cumsum(dim=0)
#
# print("cum_counts=",cum_counts)
# estimates = cum_counts / cum_counts.sum(dim=1, keepdims=True)
# print('3',estimates )
# plt.figure(figsize=(6, 4.5))
# for i in range(6):
#     plt.plot(estimates[:, i].numpy(),
#                  label=("P(die=" + str(i + 1) + ")"))
# plt.axhline(y=0.167, color='black', linestyle='dashed')
# plt.gca().set_xlabel('Groups of experiments')
# plt.gca().set_ylabel('Estimated probability')
# plt.legend()
# plt.show()